package com.zzj.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zzj.bean.AccountBean;
import com.zzj.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private AccountService service;

    @RequestMapping("/add")
    public String add(AccountBean accountBean){
        accountBean.setUpdatetime(new Date());
        boolean add = service.add(accountBean);
        if (add){
            return "forward:/account/findAll";
        }
        return "error";
    }

    @RequestMapping("/del")
    public String del(
            @RequestParam(required = false,defaultValue = "1") int pageNum,
            @RequestParam(required = false,defaultValue = "3") int pageSize,
            int id,
            Model model){
        boolean del = service.del(id);
        getData(pageNum,pageSize,model);
        if (del){
            return "account";
        }
        return "error";
    }

    @RequestMapping("/update")
    public String update(AccountBean accountBean){
        boolean update = service.update(accountBean);
        if (update){
            return "ok";
        }
        return "error";
    }

    @RequestMapping("/findAll")
    public String findAll(
            @RequestParam(required = false,defaultValue = "1") int pageNum,
            @RequestParam(required = false,defaultValue = "3") int pageSize,
            Model model){
            getData(pageNum,pageSize,model);
        return "account";
    }

    @RequestMapping("/findById")
    @ResponseBody
    public AccountBean findById(int id){
        return service.findById(id);
    }

    @RequestMapping("/transform")
    public String transformMoneyById(int from,int to,double money){
        boolean b = service.transformMoneyById(from, to, money);
        if (b){
            return "ok";
        }
        return "error";
    }

    private void getData(int pageNum, int pageSize, Model model){
        PageHelper.startPage(pageNum,pageSize);
        List<AccountBean> list = service.findAll();
        PageInfo<AccountBean> info = new PageInfo<>(list);
        model.addAttribute("data",info);
        System.out.println(info);
    }
}
